package service

import (
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateArticle
//@description: 创建Article记录
//@param: article model.Article
//@return: err error

func CreateArticle(article model.Article) (err error) {
	err = global.GVA_DB.Create(&article).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteArticle
//@description: 删除Article记录
//@param: article model.Article
//@return: err error

func DeleteArticle(article model.Article) (err error) {
	err = global.GVA_DB.Delete(&article).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteArticleByIds
//@description: 批量删除Article记录
//@param: ids request.IdsReq
//@return: err error

func DeleteArticleByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]model.Article{},"id in ?",ids.Ids).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateArticle
//@description: 更新Article记录
//@param: article *model.Article
//@return: err error

func UpdateArticle(article model.Article) (err error) {
	err = global.GVA_DB.Save(&article).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetArticle
//@description: 根据id获取Article记录
//@param: id uint
//@return: err error, article model.Article

func GetArticle(id uint) (err error, article model.Article) {
	err = global.GVA_DB.Where("id = ?", id).First(&article).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetArticleInfoList
//@description: 分页获取Article记录
//@param: info request.ArticleSearch
//@return: err error, list interface{}, total int64

func GetArticleInfoList(info request.ArticleSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&model.Article{})
    var articles []model.Article
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.CateId != 0 {
        db = db.Where("`cate_id` = ?",info.CateId)
    }
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&articles).Error
	return err, articles, total
}